/**
 * Copyright (c) 2012 Nokia Corporation. 
 */

package com.nokia.example.tictactoe.console;

import java.util.Calendar;
import java.util.Date;

/**
 * A log for general messages. Provides an interface for renderer but doesn't
 * know how to render itself.
 */
public class Log {
	// Constants
	public static final int MAX_ENTRY_COUNT = 10;
	
	// Members
	private static Log _instance;
	private String[] _logEntries = null;
	private Renderer _renderer = null;
	
	/** 
	 * @return The singleton instance of the log.
	 */
	public static Log instance() {
		if (_instance == null) {
			_instance = new Log();
		}
		
		return _instance;
	}
	
	/**
	 * Constructor.
	 */
	private Log() {
		_logEntries = new String[MAX_ENTRY_COUNT];
	}
	
	/**
	 * @param renderer The instance that renders the log content.
	 */
	public static void setRenderer(Renderer renderer) {
		instance()._renderer = renderer;
	}
	
	/**
	 * Adds the given entry into the array of entries.
	 * @param entry The new entry to add.
	 */
	public static void addEntry(final String entry) {
		Log self = instance();
		StringBuffer newEntry = new StringBuffer();
		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		
		newEntry.append(calendar.get(Calendar.HOUR_OF_DAY));
		newEntry.append(":");
		newEntry.append(calendar.get(Calendar.MINUTE));
		newEntry.append(":");
		newEntry.append(calendar.get(Calendar.SECOND));
		newEntry.append(": ");		
		newEntry.append(entry);
		
		// See if there's a spot available in the array
		for (int i = 0; i < MAX_ENTRY_COUNT; ++i) {
			if (self._logEntries[i] == null) {
				self._logEntries[i] = newEntry.toString();
				
				if (self._renderer != null) {
					self._renderer.onRenderRequest();
				}
				
				return;
			}
		}

		// No spots available. Remove the oldest entry and then add the new one
		// into the array
		self._logEntries[0] = null;
		
		for (int i = 1; i < MAX_ENTRY_COUNT; ++i) {
			self._logEntries[i - 1] = self._logEntries[i]; 
		}
		
		self._logEntries[MAX_ENTRY_COUNT - 1] = newEntry.toString();

		if (self._renderer != null) {
			self._renderer.onRenderRequest();
		}

	}
	
	/**
	 * Clears the entry array.
	 */
	public static void clear() {
		Log self = instance();
		
		for (int i = 0; i < MAX_ENTRY_COUNT; ++i) {
			self._logEntries[i] = null;
		}
		
		if (self._renderer != null) {
			self._renderer.onRenderRequest();
		}
	}
	
	/**
	 * @return The log entries.
	 */
	public final String[] logEntries() {
		return _logEntries;
	}
	
	/**
	 * Interface for the UI element that renders the log.
	 */
	public interface Renderer {
		void onRenderRequest();
	}
}
